﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace CommonLib
{
	public class QuadTreeManagerBase : MonoBehaviour
	{
		[SerializeField]
		float Width = 64;
		[SerializeField]
		float Height = 64;

		[SerializeField]
		float CellMinSize = 1;

		public GameObject prefab;

		public QuadTreeNode treeNode;

		public QuadTreeNode GetRoot()
		{
			if (null == treeNode)
				treeNode = new QuadTreeNode(Vector3.zero, new Vector3(Width, Height, 10), QuadTreeNodeType.None, CellMinSize, 0, null);
			return treeNode;
		}

		private void Awake()
		{
			
		}

		float duration = 0.2f;
		float curDuration = 0;
		private void Update()
		{
			if ((curDuration += Time.deltaTime) >= duration)
			{
				curDuration = 0;
				float x = Random.Range(-Width / 4, Width / 4);
				float y = Random.Range(-Height / 4, Height / 4);
				Vector3 pos =  new Vector3(x, y, 0);
				int instanceid = GetRoot().CheckObject(pos);
				//QuadTreeNode treeNode = GetRoot();
				//GameObject temp = Instantiate(prefab);
				//temp.transform.position = new Vector3(x, y, 0); temp.SetActive(false); temp.SetActive(true);
				if (instanceid > 0 && QuadTreeNodeHolder.Instance.GetNode(instanceid).Count < 1)
				{
					GameObject temp = Instantiate(prefab);
					temp.transform.position = new Vector3(x, y, 0); temp.SetActive(false); temp.SetActive(true);
					QuadTreeNodeHolder.Instance.GetNode(instanceid).AddNodeReference(temp.AddComponent<QuadTreeReference>());
				}
				else
				{
					Debug.Log("位置重复 :" + instanceid);
					//QuadTreeNodeHolder.Instance.GetNode(instanceid).DrawCubeSelf();
				}
			}
		}



		private void OnDrawGizmos()
		{
			QuadTreeNode treeNode = GetRoot();
			//Gizmos.color = Color.black;
			//Debug.Log(treeNode.CheckObject(prefab.transform.position));
			//Gizmos.DrawWireCube(gameObject.transform.position, new Vector3(Width, Height, 1));
			treeNode.DrawCude();
			//Debug.Log(treeNode.CheckObject(gameObject));
			//Debug.Log(treeNode.CheckObject(gameObject,gameObject.GetComponent<BoxCollider>().bounds));
			//Debug.Log(QuadTreeNodeHolder.Instance.Count);
			//QuadTreeNodeHolder.Instance.GetNode(gameObject.GetComponent<QuadTreeReference>().NodeInstance).DrawCubeself();
		}
	}
}